"""
上传excel数据并解析到数据库
"""

import base64
import io
import os
from typing import List, Callable, Literal
from flask import request
from dash import (
    get_app,
    dcc,
    html,
    callback,
    Output,
    Input,
    State,
    register_page,
    MATCH,
    no_update
)
from ddbtools import BaseCRUD, get_table_columns, DBDf
import pandas as pd
from gypb.db import get_db
from gypb.component import DirFilesTable
from gypb.apps.manager_judge import (
    get_manager_info,
    generate_report,
    get_manager_info_score,
    get_product_data,
    get_product_score,
)
import feffery_antd_components as fac
from gypb.config import settings
from pathlib import Path

basedir = settings.custom_dir
if not basedir:
    basedir = Path.home().joinpath(".gypb")

dir = Path(basedir).joinpath("manager_judge")
if not os.path.exists(dir):
    os.makedirs(dir)


register_page(__name__, name="管理人评估报告", order=5)

name = "manager_judge"
filetable = DirFilesTable(
    name=name,
    dir=str(dir),
    enable_delete=True,
    enable_download=True,
)
def layout():
    return html.Div(
        [
            dcc.Upload(
                id={"type": "upload-manager-query-docx", "index": name},
                children=html.Div(["请在此上传管理人尽调问卷"]),
                multiple=False,
                style={
                    "width": "100%",
                    "height": "60px",
                    "lineHeight": "60px",
                    "borderWidth": "1px",
                    "borderStyle": "dashed",
                    "borderRadius": "5px",
                    "textAlign": "center",
                    "margin": "10px",
                },
            ),
            html.Div(id={"type": 'uploaded-manager-query-docx', "index": name}),
            dcc.Upload(
                id={"type": "upload-netvalue-xlsx", "index": name},
                children=html.Div(["请在此上传净值模板"]),
                multiple=False,
                style={
                    "width": "100%",
                    "height": "60px",
                    "lineHeight": "60px",
                    "borderWidth": "1px",
                    "borderStyle": "dashed",
                    "borderRadius": "5px",
                    "textAlign": "center",
                    "margin": "10px",
                },
            ),
            html.Div(id={"type": 'uploaded-netvalue-xlsx', "index": name}),
            fac.AntdButton(
                "生成管理人评估报告",
                id={"type": "button-generate-report", "index": name},
                type="primary",
            ),
            fac.AntdModal(id={"type": 'modal_generate_report', "index": name}, title='生成报告进度'),
            filetable.layout,
            html.Div(id={"type": 'error_info', "index": name},style={'color': 'red'}),
        ]
    )

@callback(
    Output({"type": "uploaded-manager-query-docx", "index": MATCH}, 'children'),
    Output({"type": 'error_info', "index": MATCH}, "children",allow_duplicate=True),
    Input({"type": "upload-manager-query-docx", "index": MATCH}, 'contents'),
    State({"type": "upload-manager-query-docx", "index": MATCH}, 'filename'),
    prevent_initial_call=True,
)
def display_uploaded_manager_query_docx(contents, filename):
    if contents is not None:
        return filename,None

@callback(
    Output({"type": "uploaded-netvalue-xlsx", "index": MATCH}, 'children'),
    Output({"type": 'error_info', "index": MATCH}, "children",allow_duplicate=True),
    Input({"type": "upload-netvalue-xlsx", "index": MATCH}, 'contents'),
    State({"type": "upload-netvalue-xlsx", "index": MATCH}, 'filename'),
    prevent_initial_call=True,
)
def display_uploaded_manager_query_docx(contents, filename):
    if contents is not None:
        return filename,None
    
@callback(
    Output({"type": "dirfiles-table", "index": MATCH}, "data"),
    Output({"type": 'error_info', "index": MATCH}, "children",allow_duplicate=True),
    Input({"type": "button-generate-report", "index": MATCH}, "nClicks"),
    State({"type": "upload-manager-query-docx", "index": MATCH}, "contents"),
    State({"type": "upload-netvalue-xlsx", "index": MATCH}, "contents"),
    # State("upload-manager-netvalue-xlsx", "contents"),
    prevent_initial_call=True,
)
def generate_manager_judge_report(nClicks, manager_info_docx,netvalue_excel):
    if nClicks:
        try:
            context = {}
            # 解析管理人尽调问卷
            content_type, content_string = manager_info_docx.split(",")
            manager_info_decoded = base64.b64decode(content_string)
            manager_info = get_manager_info(io.BytesIO(manager_info_decoded))
            context.update(manager_info)
            # 尽调问卷基础信息打分
            info_score = get_manager_info_score(manager_info)
            context.update(info_score)
            # 产品信息数据，字典（统计日期+产品统计数据）
            content_type, content_string = netvalue_excel.split(",")
            netvalue_excel_decoded = base64.b64decode(content_string)
            product_data = get_product_data(io.BytesIO(netvalue_excel_decoded),dir,manager_info["company_name"])
            context.update(product_data)
            # 产品信息打分
            product_score = get_product_score(product_data['product_data'])
            context.update(product_score)
            context["total_w_score"] = context["manager_info_w_score"] + context["product_w_score"]
            generate_report(
                "src/gypb/apps/manager_judge/test_report.docx", context, dir
            )
            return filetable.get_data(),no_update
        except Exception as e:
            # 捕获异常并返回错误信息
            error_message = f'发生错误: {str(e)}'
            return no_update, error_message  # 返回空正常输出和错误信息
